package com.demo2do.boyle.client.handler.impl;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;

import com.demo2do.boyle.client.Constant;
import com.demo2do.boyle.client.handler.ValidateCodeHandler;
import com.demo2do.boyle.common.entity.protocol.sms.SmsType;
import com.demo2do.boyle.common.handler.SmsHandler;
import com.demo2do.core.entity.Result;

/**
 * 
 * @author Wilson
 */
@Component("validateCodeHandler ")
public class ValidateCodeHandlerImpl implements ValidateCodeHandler {

    private static final Logger logger = LoggerFactory.getLogger(ValidateCodeHandlerImpl.class);

    @Autowired
    private CacheManager cacheManager;

    @Autowired
    private SmsHandler smshandler;

    /*
     * (non-Javadoc)
     * @see com.demo2do.boyle.client.handler.ValidateCodeHandler#sendValidateCode(java.lang.String, java.lang.String, com.demo2do.boyle.client.entity.protocol.sms.SmsType)
     */
    public Result sendValidateCode(String phone, String module, SmsType smsType) {

        Result result = new Result();

        Cache cache = cacheManager.getCache(Constant.CACHE_VALIDATE_CODE);
        String cacheKey = Constant.CACHE_VALIDATE_CODE_PREFIX + module + "_" + phone;

        // if already exists, return fail
        Cache.ValueWrapper valueWrapper = cache.get(cacheKey);
        if(valueWrapper != null) {
            return result.fail().message("60秒内不能重新发送");
        }

        // generate validate code
        String validateCode = Integer.toString((int)(Math.random()*9000)+1000);

        // save validate code in cache
        cache.put(cacheKey, validateCode);
        logger.info("Save validate code[" + validateCode + "] with key[" + cacheKey +  "].");

        // send sms
        result = smshandler.sendValidateCode(phone, validateCode, smsType);

        return result;
    }

    /*
     * (non-Javadoc)
     * @see com.demo2do.boyle.client.handler.ValidateCodeHandler#validateCode(java.lang.String, java.lang.String, java.lang.String)
     */
    public boolean validateCode(String phone, String module, String code) {

        Cache cache = cacheManager.getCache(Constant.CACHE_VALIDATE_CODE);
        String cacheKey = Constant.CACHE_VALIDATE_CODE_PREFIX + module + "_" + phone;
        Cache.ValueWrapper valueWrapper = cache.get(cacheKey);

        logger.info("From cache get with key[" + cacheKey +  "].");
        if(StringUtils.isNotBlank(code) && valueWrapper != null) {
            logger.info("From cache get code[" + (String)valueWrapper.get() + "] with key[" + cacheKey +  "].");
            return StringUtils.equals((String)valueWrapper.get(), code);
        }

        return false;
    }

}
